﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

namespace Base
{
    public interface INameable //要求必须具有Name属性
    {
        string Name
        {
            get;
            set;
        }
    }
    public class baseItem<T> : INameable, IComparable<T>, IEquatable<T>
        where T : class, INameable, IComparable<T>,IEquatable<T>
    {
        public string Name
        {
            get;
            set;
        }
        public int CompareTo(T t)
        {
            return String.Compare(this.Name, t.Name);
        }
        public int CompareTo(object t)
        {
            return String.Compare(this.Name, ((T)t).Name);
        }
        public bool Equals(	T other)
        {
            return (this.Name==other.Name);
        }
        public override bool Equals(	object other)
        {
            return (this.Name==((T)other).Name);
        }
        
        public override int GetHashCode()
        {
            return base.GetHashCode() + Name.GetHashCode();
        }

    }

    public class baseList<T> : List<T>
        where T : class, INameable//, IComparable<T>
    {
        //寻找对象
        public bool find(string name, out T obj)
        {
            foreach (T t in this)
            {
                if (t.Name == name)
                {
                    obj = t;
                    return true;
                }
            }
            obj = null;
            return false;
        }
        public bool find(string name)
        {
            foreach (T t in this)
            {
                if (t.Name == name)
                {
                    return true;
                }
            }
            return false;
        }
        //索引器：用名字来访问对象
        public T this[string name]
        {
            get
            {
                foreach (T t in this)
                {
                    if (t.Name == name)
                    {
                        return t;
                    }
                }
                return null;
            }
            set
            {
                T targetT = null;
                foreach (T t in this)
                {
                    if (t.Name == name)
                    {
                        targetT = t;
                    }
                }
                if (null == targetT)
                {
                    Add(value);
                }
                else
                {
                    targetT = value;
                }
            }
        }
    }
}
